package ohc.login

import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.Text
import java.util.concurrent.ConcurrentHashMap

/**
 * 假人管理器
 */
object FakePlayerManager {
    
    private const val FAKE_PLAYER_PREFIX = "§7[假人] §r"
    
    // 待自动登录的假人名称
    private val pendingFakePlayers: ConcurrentHashMap<String, Unit> = ConcurrentHashMap()
    
    /**
     * 记录即将生成的假人名称，等待玩家加入时自动登录
     */
    fun scheduleFakePlayerLogin(playerName: String) {
        val normalizedName = playerName.lowercase()
        pendingFakePlayers[normalizedName] = Unit
        Ohc_login.logger.info("已记录假人 $playerName，等待加入时自动登录")
    }
    
    /**
     * 玩家加入时检查是否是待登录的假人，如果是则执行登录
     * @return true 如果是假人并已处理
     */
    fun tryAutoLogin(player: ServerPlayerEntity): Boolean {
        val normalizedName = player.gameProfile.name.lowercase()
        if (pendingFakePlayers.remove(normalizedName) == null) {
            return false
        }
        
        val uuid = player.uuid
        if (!LoginManager.isLoggedIn(uuid)) {
            LoginManager.completeLogin(uuid)
            setFakePlayerPrefix(player)
            Ohc_login.logger.info("假人 ${player.gameProfile.name} 已自动登录")
        }
        return true
    }
    
    private const val NOT_LOGGED_IN_PREFIX = "§c[未登录] §r"
    
    /**
     * 玩家加入时清除旧称号并设置未登录称号
     */
    fun setNotLoggedInPrefix(player: ServerPlayerEntity) {
        val server = (player.getEntityWorld() as net.minecraft.server.world.ServerWorld).server
        val scoreboard = server.scoreboard
        val playerName = player.gameProfile.name
        
        // 先从旧 team 移除
        val oldTeam = scoreboard.getScoreHolderTeam(playerName)
        if (oldTeam != null && oldTeam.name.startsWith("ohc_")) {
            scoreboard.removeScoreHolderFromTeam(playerName, oldTeam)
        }
        
        // 设置未登录称号
        val teamName = "ohc_${playerName.take(12)}"
        var team = scoreboard.getTeam(teamName)
        if (team == null) {
            team = scoreboard.addTeam(teamName)
        }
        team.prefix = Text.literal(NOT_LOGGED_IN_PREFIX)
        scoreboard.addScoreHolderToTeam(playerName, team)
    }
    
    /**
     * 为假人设置称号前缀
     */
    private fun setFakePlayerPrefix(player: ServerPlayerEntity) {
        val server = (player.getEntityWorld() as net.minecraft.server.world.ServerWorld).server
        val scoreboard = server.scoreboard
        val playerName = player.gameProfile.name
        
        val teamName = "ohc_${playerName.take(12)}"
        var team = scoreboard.getTeam(teamName)
        if (team == null) {
            team = scoreboard.addTeam(teamName)
        }
        team.prefix = Text.literal(FAKE_PLAYER_PREFIX)
        scoreboard.addScoreHolderToTeam(playerName, team)
    }
    
    /**
     * 检查是否是 /player spawn 命令
     * @return 如果是则返回假人名称，否则返回 null
     */
    fun parsePlayerSpawnCommand(command: String): String? {
        val trimmed = command.trim()
        if (!trimmed.lowercase().startsWith("player ")) {
            return null
        }
        
        val parts = trimmed.split("\\s+".toRegex())
        // 格式: player <name> spawn [...]
        if (parts.size < 3) {
            return null
        }
        
        if (!parts[2].equals("spawn", ignoreCase = true)) {
            return null
        }
        
        return parts[1]
    }
}
